import {init} from '../../utils/realtime';
import {getQuery} from '../../utils/Av';
export async function sendContent (toId, content, callback) {
  var user = AV.User.current ();
  var realtime = init ();

  // Jerry 登录
  realtime
    .createIMClient (toId)
    .then (function (jerry) {
      jerry.off (AV.Event.MESSAGE, callback);
      jerry.on (AV.Event.MESSAGE, callback);
    })
    .catch (console.error);

  return realtime
    .createIMClient (user.toJSON ().objectId)
    .then (function (tom) {
      // 创建与Jerry之间的对话
      return tom.createConversation ({
        members: [toId],
        unique: true,
        name: 'talk_room',
      });
    })
    .then (conversation => {
      return conversation.join ();
    })
    .then (conversation => {
      return conversation.send (new AV.TextMessage (content));
    })
    .catch (console.error);
}

export async function getMessages (toId) {
  var user = AV.User.current ();
  var realtime = init ();
  return realtime
    .createIMClient (user.toJSON ().objectId)
    .then (function (tom) {
      return tom.createConversation ({
        members: [toId],
        unique: true,
        name: 'talk_room',
      });
    })
    .then (conversation => {
      return conversation
        .queryMessages ({
          limit: 10, // limit 取值范围 1~1000，默认 20
        })
        .then (function (messages) {
          // 最新的十条消息，按时间增序排列
          return messages.map (item => item.toJSON ());
        });
    });
}

export async function get_user_information_get_duifang_information (toId) {
  var user = AV.User.current ();
  var to_user = await getQuery ('_User').equalTo ('objectId', toId).first ();
  return {from: user.toJSON (), to: to_user.toJSON ()};
}
